const { Comment, User } = require('../model')
const { addComment } = require('../service/comment')
const { getUser, isExistUser, createUser } = require('../service/user')

/**
 * 注册页面
 */
async function signinPage(ctx, next) {
  await ctx.render("signin")
}

// 注册功能
async function signupApi(ctx, next) {
  let { username, password, repassword } = ctx.request.body

  // 判断必要信息是否填写
  if (!username || !password || !repassword) {
    return ctx.render("message", {
      code: 40007,
      msg: "注册失败",
      reasons: ["注册信息填写不正确或不完整"],
      url: "javascript:window.history.back()"
    })
  }

  //判断两次密码是否一致
  if (password != repassword) {
    return ctx.render('message', {
      code: 40007,
      msg: "注册失败",
      reasons: ["两次输入密码不一致"],
      url: "javascript:window.history.back()"
    })
  }

  // 判断用户名是否存在
  let user = await isExistUser(username)

  if (user) {
    return ctx.render('message', {
      code: 40007,
      msg: "注册失败",
      reasons: ["此用户已经被注册"],
      url: "javascript:window.history.back()"
    })
  }


  // 注册
  try {
    await createUser({ username, password })
    await ctx.render('message', {
      msg: "注册成功",
      url: "/signin"
    })
  } catch (err) {
    await ctx.render('message', {
      code: 40007,
      msg: "注册失败",
      reasons: ["数据写入失败"],
      url: "javascript:window.history.back()"
    })
  }

}

/**
 * 登录页面
 */
async function signupPage(ctx, next) {
  await ctx.render("signup")
}

/**
 * 登录
 */
async function doLogin(ctx, next) {
  // 获取用户信息
  let { username, password } = ctx.request.body

  if (!username || !password) {
    return ctx.render("message", {
      code: 40008,
      msg: "登录失败",
      reasons: ["登录信息填写不正确"],
      url: "javascript:window.history.back()"
    })
  }

  const result = await getUser({ username, password })

  // 验证密码是否一致
  if (!result) {
    return ctx.render("message", {
      msg: "登录失败",
      reasons: ["用户名或者密码错误", "确认你已拥有账号"],
      url: "javascript:window.history.back()"
    })
  }

  ctx.session.user = { ...result }
  await ctx.render("message", {
    msg: "登录成功",
    url: "/"
  })
}


/**
 * 个人中心页面
 */
async function profilePage(ctx, next) {
  await ctx.render("user")
}

// 注销
async function layout(ctx, next) {
  delete ctx.session.user
  await ctx.redirect("/signin")
}

/**
 * 添加评论
 */
async function addCommentApi(ctx, next) {
  // 获取数据 商品id 及 用户信息 及 评论内容
  const { itemId } = ctx.params
  const { id: userId } = ctx.session.user
  const { content } = ctx.request.body

  try {
    await addComment({ itemId, userId, content })
    ctx.body = {
      code: 200,
      msg: "添加评论成功"

    }
  } catch (err) {
    console.log(err)
    ctx.body = {
      code: 40002,
      msg: "添加评论失败"
    }
  }
}

// 设置头像
async function uploadImg(ctx, next) {
  const { id } = ctx.session.user.dataValues
  const { avatar } = ctx.request.files
}

// 更改密码

module.exports = {
  doLogin,
  signinPage,
  layout,
  signupPage,
  signupApi,
  profilePage,
  addCommentApi
}
